package com.ruoyi.common.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.ruoyi.common.core.exception.UtilException;

import java.nio.charset.Charset;

public class JsonUtils<T> {
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class<T> clazz;

    public JsonUtils(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    public byte[] serialize(T t) throws UtilException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }


    public T deserialize(byte[] bytes) throws UtilException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
    }

    public   String jsonSerialize(T t) throws UtilException
    {
        if (t == null)
        {
            return "";
        }
        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName);
    }



    public  T jsonDeserialize(String s) throws UtilException
    {
        if (!StringUtils.isNotNull(s))
        {
            return null;
        }
        return JSON.parseObject(s,clazz , JSONReader.Feature.SupportAutoType);
    }
}
